package com.googlecode.olabs.clients.fileSync.contacts;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import com.googlecode.olabs.common.client.contact.Contact;

public class ShellListWrapper implements ListModel {

	public static final ShellListWrapper wrap(ContactLibrary library) {
		final ShellListWrapper wrapper = new ShellListWrapper(library);
		library.addObserver(new ContactLibrary.ContactLibraryObserver() {
			public void contactListUpdated() {
				wrapper.contactLibraryChanged();
			}

			public void contactUpdated(Contact contact) {
			}
		});
		return wrapper;
	}

	private final Collection<ListDataListener> m_listeners;
	private final ContactLibrary m_library;
	private List<Contact> m_contacts;

	private ShellListWrapper(ContactLibrary library) {
		m_listeners = new ArrayList<ListDataListener>();
		m_library = library;
		m_contacts = m_library.asList();
	}

	public void addListDataListener(ListDataListener l) {
		m_listeners.add(l);
	}

	public Object getElementAt(int index) {
		return m_contacts.get(index).getId().getValue().get(0);
	}

	public Contact getContactAt(int index) {
		return m_contacts.get(index);
	}

	public int getSize() {
		return m_contacts.size();
	}

	private void contactLibraryChanged() {
		m_contacts = m_library.asList();
		ListDataEvent event = new ListDataEvent(this,
				ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1);
		for (ListDataListener listener : m_listeners) {
			listener.contentsChanged(event);
		}
	}

	public void removeListDataListener(ListDataListener l) {
		m_listeners.remove(l);
	}
}
